package com.study.study;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/14 20:36
 */
class ShareData {
    private int number = 1;//A 1  | B 2 |C 3
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print5() {
        lock.lock();
        try {
            //1等待（while可以解决虚假唤醒）
            while (number != 1) {
                //等待
                c1.await();
            }
            //2 干活
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3 通知
            number = 2;
            c2.signal();//通知2
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }
    }

    public void print10() {
        lock.lock();
        try {
            //1等待（while可以解决虚假唤醒）
            while (number != 2) {
                //等待
                c2.await();
            }
            //2 干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3 通知
            number = 3;
            c3.signal();//通知2
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }
    }

    public void print15() {
        lock.lock();
        try {
            //1等待（while可以解决虚假唤醒）
            while (number != 3) {
                //等待
                c3.await();
            }
            //2 干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3 通知
            number = 1;
            c1.signal();//通知2
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 三个线程 按顺序 A ->B ->C
 * A打印5次
 * B 打印10次
 * C 打印15次
 */
public class conditionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.print5();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.print10();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.print15();
            }
        }, "C").start();
    }
}
